<template>
  <el-select
  value-key="id"
  :model-value="modelValue"
  @update:model-value="handleChange"
>
  <el-option
    v-for="good in filteredGoods"
    :key="good.id"
    :label="`${good.code} - ${good.name}`"
    :value="good"
  />
</el-select>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { Good } from '@/types/bom'

const props = defineProps<{
  modelValue: Good | null
}>()

const emit = defineEmits(['update:modelValue'])

// 本地存储的商品数据
const localGoods = ref<Good[]>([])
const loading = ref(false)
const error = ref(false)

// 获取商品数据
const fetchGoods = async () => {
  try {
    loading.value = true
    error.value = false
    
    // 修改请求处理
    const response = await axios.get('http://localhost:8084/good/getAll')
    
    // 调试输出原始数据结构
    console.log('API响应数据:', response.data)
    
    // 类型检查和处理
    let goodsData: Good[] = []
    
    if (Array.isArray(response.data)) {
      // 如果直接返回数组
      goodsData = response.data
    } else if (response.data?.data && Array.isArray(response.data.data)) {
      // 如果返回的是 { data: [...] } 结构
      goodsData = response.data.data
      console.log(goodsData)
    } else {
      throw new Error('无效的响应数据结构')
    }
    
    localGoods.value = goodsData.map(g => ({
      ...g,
      disabled: g.status !== 0
    }))
    
  } catch (err) {
    console.error('商品加载失败:', err)
    error.value = true
    ElMessage.error(`商品加载失败: ${err.message}`)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  fetchGoods()
})

// 过滤可用商品
const filteredGoods = computed(() => {
  return localGoods.value.filter(g => !g.disabled)
})

// 处理选择变化
const handleChange = (value: Good | null) => {
  if (value) {
    const newValue = {
      ...value,
      details: { ...value.details }
    }
    emit('update:modelValue', newValue)
  } else {
    emit('update:modelValue', null)
  }
}

// 暴露刷新方法
defineExpose({
  refresh: fetchGoods
})
</script>

<style scoped>
.is-loading {
  animation: rotating 2s linear infinite;
  margin-right: 8px;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>